import { reactive } from "vue";
import { LowCodeImp, FormImp } from "./type";
const lowCodeInstance = Symbol("lowCodeInstance");

export class Form implements FormImp {
  private [lowCodeInstance]: LowCodeImp;
  formRefs: any = new Map();
  customSchemasRenders = reactive(new Map()) 
  constructor(lowcode: LowCodeImp) {
    this[lowCodeInstance] = lowcode as LowCodeImp;
  }

  setSchemas(key: string = 'default', schemas: any){
    this.customSchemasRenders.set(key,schemas)
  }
  

  getSchemas(key: string  = 'default') {
    return this.customSchemasRenders.get(key)
  }

  async getValidateData() {
    const params = {};
    const validatePromises: Promise<boolean>[] = [];
    for (const [key, value] of this.formRefs.entries()) {
      const formRef = this.getFormRefs(key);
      if (!formRef?.value) continue; // 跳过无效的表单引用
      validatePromises.push(formRef.value.validate());
    }
    return new Promise(async (resolve, reject) => {
      try {
        const results = await Promise.all(validatePromises);
        console.log("所有表单校验通过:", results);
        // message.success("所有表单校验成功");
        results.forEach((result) => {
          Object.assign(params, result);
        });
        resolve(params);
      } catch (error) {
        reject(error);
      }
    });
  }

  getFormData() {
    const params = {};
    this.getAllFormRefs().forEach((_value: any, key: any) => {
      const formRef = this.getFormRefs(key);
      if (formRef) {
        const formValue = formRef.value.getFieldsValue();
        Object.assign(params, formValue);
      }
    });
    return params;
  }

  setFormRefs(key: string, ref: any) {
    this.formRefs.set(key, ref);
  }

  getFormRefs(key: string) {
    return this.formRefs.get(key);
  }

  getAllFormRefs() {
    return this.formRefs;
  }
}
